package com.mars.module.oss.strategy;


import com.mars.framework.exception.ServiceException;
import com.mars.module.oss.common.enums.FileUploadTypeEnums;
import com.mars.module.oss.factory.StrategyFactory;
import lombok.AllArgsConstructor;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 本地上传策略
 *
 * @author 程序员Mars
 * @version 1.0
 * @date 2024-02-29 09:21:50
 */
@Service
@AllArgsConstructor
public class LocalUploadStrategy implements Strategy {

    @Resource
    private Environment environment;

    @Override
    public String upload(MultipartFile file) {

        //图片校验（图片是否为空,图片大小，上传的是不是图片、图片类型（例如只能上传png）等等）
        if (file.isEmpty()) {
            throw new ServiceException("请选择上传类型");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = "." + originalFilename.split("\\.")[1];
        //生成一个新的文件名（以防有重复的名字存在导致被覆盖）
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid + ext;
        //拼接图片上传的路径 url+图片名
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\image\\";
        String path = pre + newName;
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String port = environment.getProperty("server.port");
        return "http://localhost:" + port +"/static/image/"+ newName;
    }

    @Override
    public void afterPropertiesSet() {
        StrategyFactory.register(FileUploadTypeEnums.LOCAL, this);
    }
}
